package com.example.search.vm

import androidx.annotation.MainThread
import androidx.lifecycle.viewModelScope
import com.example.common.vm.BaseViewModel
import com.example.search.intent.SearchViewIntent
import com.example.search.model.SearchRepository
import com.example.search.state.SearchUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class SearchViewModel @Inject constructor(private val repository:SearchRepository):BaseViewModel<SearchViewIntent>(){

    private val _uiState = MutableStateFlow<SearchUiState>(SearchUiState.LoadEmpty)
    val uiState:StateFlow<SearchUiState> = _uiState.asStateFlow()


    override fun dispatchIntent(intent: SearchViewIntent) {
        when(intent){
            is SearchViewIntent.LoadSimpleVideoListByKeyword -> loadSimpleVideoList(intent.keyword,intent.page,intent.pageSize)
        }
    }

    private fun loadSimpleVideoList(keyword:String,page:Int,pageSize:Int){
        viewModelScope.launch(Dispatchers.IO){

            try {
                withContext(Dispatchers.Main){
                    repository.getSimpleVideoByKeyword(keyword,page,pageSize).collect{
                        if(it.isNotEmpty()){
                            _uiState.value = SearchUiState.LoadSimpleVideoSuccess(it)
                        }else{
                            _uiState.value = SearchUiState.LoadSimpleVideoFail("没有数据")
                        }
                    }
                }
            }catch (e:Exception){
                e.printStackTrace()
                _uiState.value = SearchUiState.LoadSimpleVideoFail("没有数据!!!")
            }finally {
                cancel()
            }
        }



    }


}